package service;

import model.Movie;
import model.Show;

import util.FileHandler;
import java.util.ArrayList;
import java.util.List;

public class MovieService {
    private static final String MOVIE_FILE = "movies.dat";
    private List<Movie> movies;

    public MovieService() {
        movies = FileHandler.loadData(MOVIE_FILE);
        if (movies == null) movies = new ArrayList<>();
    }

    // 保存影片数据
    public void saveMovies() {
        FileHandler.saveData(movies, MOVIE_FILE);
    }

    // 列出所有影片
    public List<Movie> listAllMovies() {
        return new ArrayList<>(movies);
    }

    // 根据ID获取影片
    public Movie getMovieById(String id) {
        for (Movie movie : movies) {
            if (movie.getId().equals(id)) {
                return movie;
            }
        }
        return null;
    }

    // 添加影片
    public boolean addMovie(Movie movie) {
        for (Movie m : movies) {
            if (m.getId().equals(movie.getId())) {
                return false;
            }
        }
        movies.add(movie);
        saveMovies();
        return true;
    }

    // 修改影片
    public boolean updateMovie(Movie updatedMovie) {
        for (int i = 0; i < movies.size(); i++) {
            if (movies.get(i).getId().equals(updatedMovie.getId())) {
                movies.set(i, updatedMovie);
                saveMovies();
                return true;
            }
        }
        return false;
    }

    // 删除影片（检查是否有排片）
    public boolean deleteMovie(String id, ShowService showService) {
        for (Show show : showService.listAllShows()) {
            if (show.getMovieId().equals(id)) {
                return false;
            }
        }
        for (int i = 0; i < movies.size(); i++) {
            if (movies.get(i).getId().equals(id)) {
                movies.remove(i);
                saveMovies();
                return true;
            }
        }
        return false;
    }


    // 搜索影片（支持组合查询）
    public List<Movie> searchMovies(String name, String director, String actor) {
        List<Movie> result = new ArrayList<>();
        for (Movie movie : movies) {
            boolean match = true;
            if (name != null && !movie.getName().contains(name)) match = false;
            if (director != null && !movie.getDirector().contains(director)) match = false;
            if (actor != null && !movie.getActor().contains(actor)) match = false;
            if (match) result.add(movie);
        }
        return result;
    }
}